package org.kojo.tdrm.dao;

import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;

import org.kojo.tdrm.entity.Task;
import org.kojo.tdrm.entity.User;
import org.kojo.tdrm.persistence.PMF;

public class TaskDao extends AbstractDao<Task> {
	private static PersistenceManager pm = null;

	public TaskDao(Class<Task> entityClass) {
		super(entityClass);

	}

	@Override
	protected PersistenceManager getPersistenceManager() {
		if (pm == null || pm.isClosed()) {
			pm = PMF.get().getPersistenceManager();
		}
		System.out.println("Return PM=" + pm);
		return pm;
	}

	@Override
	public void create(Task entity) {
		PersistenceManager pm = getPersistenceManager();
		User user = (User) pm
				.getObjectById(User.class, entity.getOwnedUserId());
		entity.setOwnedUser(user);
		entity.setLastUpdate(new Date());
		// user.addTaskSets(entity);
		// User b = pm.makePersistent(user);
		Transaction tx = pm.currentTransaction();
		Task b = null;
		try {
			tx.begin();
			b = pm.makePersistent(entity);
			tx.commit();
		} finally {
			if (tx.isActive()) {
				System.out.println("trans rollback");
				tx.rollback();
			}
		}
		System.out.println("after persist=" + b.getKey());
	}

	@Override
	public void edit(Task entity) {
		entity.setLastUpdate(new Date());
		super.edit(entity);
	}

	public List<Task> findByUserId(String loginName) {
		List<Task> lsTask = null;
		PersistenceManager pm = getPersistenceManager();
		Query query = pm.newQuery("select from " + Task.class.getName()
				+ " where ownedUser == u");
		query.declareParameters(User.class.getName() + " u");
		lsTask = (List<Task>) query.execute(new User(loginName));
		for(Task t:lsTask){
			System.out.println("key kind="+t.getKey().getKind()+", id="+t.getKey().getId()+", keyString="+t.getKey().toString());
			t.getOwnedUserId(); //fetch user
			t.toString(); //fetch task attr
		}
		pm.close();
		return lsTask;
	}

}
